package org.light.simpleauth;

import java.util.ArrayList;
import java.util.List;

import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.Statement;
import org.light.domain.StatementList;
import org.light.generator.Generator;
import org.light.utils.WriteableUtil;

public class EncryptUtilGenerator extends Generator{
	protected Domain userDomain;

	public Domain getUserDomain() {
		return userDomain;
	}

	public void setUserDomain(Domain userDomain) {
		this.userDomain = userDomain;
	}

	public EncryptUtilGenerator(){
		super();
		super.fileName = "encrypt_util.rs";
		super.standardName = "EncryptUtil";
	}

	@Override
	public StatementList generateStatementList() {
		List<Writeable> sList = new ArrayList<Writeable>();
		sList.add(new Statement(1000L,0,"#![allow(unused_assignments)]"));
		sList.add(new Statement(2000L,0,"use sha1::{Sha1, Digest};"));
		sList.add(new Statement(3000L,0,""));
		sList.add(new Statement(4000L,0,"use crate::"+this.userDomain.getDomainSuffix()+"::error::Result;"));
		sList.add(new Statement(5000L,0,""));
		sList.add(new Statement(6000L,0,""));
		sList.add(new Statement(7000L,0,"pub async fn verify_password(password: String, salt: String, encrypt_password: String) -> Result<bool> {"));
		sList.add(new Statement(8000L,1,"let password_check = multi_sha1(password,salt,3);"));
		sList.add(new Statement(9000L,1,"Ok(encrypt_password==password_check)"));
		sList.add(new Statement(10000L,0,"}"));
		sList.add(new Statement(11000L,0,""));
		sList.add(new Statement(12000L,0,""));
		sList.add(new Statement(13000L,0,"pub fn mysha1(data:Vec<u8>) -> Vec<u8>{"));
		sList.add(new Statement(14000L,1,"let mut h = Sha1::new();"));
		sList.add(new Statement(15000L,1,"h.update(data);"));
		sList.add(new Statement(16000L,1,"let result = h.finalize();"));
		sList.add(new Statement(17000L,1,"result.to_vec()"));
		sList.add(new Statement(18000L,0,"}"));
		sList.add(new Statement(19000L,0,""));
		sList.add(new Statement(20000L,0,"pub fn multi_sha1(password:String, salt:String, iter:i32)-> String{"));
		sList.add(new Statement(21000L,1,"let mut b:Vec<u8> = password.as_bytes().to_vec();"));
		sList.add(new Statement(22000L,1,"let mut s:Vec<u8>  = salt.as_bytes().to_vec();"));
		sList.add(new Statement(23000L,1,"s.append(&mut b);"));
		sList.add(new Statement(24000L,1,"let mut h = Sha1::new();"));
		sList.add(new Statement(25000L,1,"h.update(s);"));
		sList.add(new Statement(26000L,1,"let mut result:Vec<u8> = h.finalize().to_vec();"));
		sList.add(new Statement(27000L,1,"h = Sha1::new();"));
		sList.add(new Statement(28000L,1,"for _i in 1 .. iter {"));
		sList.add(new Statement(29000L,2,"result = mysha1(result);"));
		sList.add(new Statement(30000L,1,"}"));
		sList.add(new Statement(32000L,1,"hex::encode(result.clone())"));
		sList.add(new Statement(33000L,0,"}"));

		return WriteableUtil.merge(sList);
	}

}
